package ai.zixing.mashibing;

/**
 * 归并排序
 */
public class MergeSort {
    public static void main(String[] args) {
        int[] arr = {1, 4, 5, 6, 2, 7, 8, 3};
        sort(arr, 0, arr.length - 1);
        print(arr);
    }

    static void sort(int[] arr, int left, int right) {
        // 分成两半
        int mid = left + (right - left) / 2;
        if (left < right) {
            // 左边排序
            sort(arr, left, mid);
            // 右边排序
            sort(arr, mid + 1, right);
            merge(arr, left, mid, right);
        }
    }

    private static void merge(int[] arr, int low, int mid, int high) {
//        int mid = rightPtr - 1;
        int[] temp = new int[high - low + 1];
        int i = low;
        int j = mid + 1;
        int k = 0;
        while (i <= mid && j <= high) {
            if (arr[i] < arr[j]) {
                temp[k++] = arr[i++];
            } else {
                temp[k++] = arr[j++];
            }
        }
        // 其中一个数组遍历完了
        while (i <= mid) {
            temp[k++] = arr[i++];
        }
        while (j <= high) {
            temp[k++] = arr[j++];
        }
        for (int m = 0; m < temp.length; m++) {
            arr[low + m] = temp[m];
        }
    }

    static void print(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}
